package com.onlyphoto.onlymall.mvp.view.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.app.SharedElementCallback
import androidx.core.view.ViewCompat
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.mvp.contract.CPhotoBrowse
import com.onlyphoto.onlymall.mvp.presenter.PPhotoBrowseImpl
import com.onlyphoto.onlymall.widget.BaseAnimCloseViewPager

import kotlin.math.min


class PhotoBrowseActivity : BaseActivity<PPhotoBrowseImpl>(), CPhotoBrowse.IVPhotoBrowse {

    private var firstDisplayImageIndex = 0
    private var newPageSelected = false
    private var mCurImage: ImageView? = null
    private var imageViewPager: BaseAnimCloseViewPager? = null
    private var pictureList: List<String>? = null

    lateinit var adapter: PagerAdapter

    var canDrag = false

    override fun setContentViewId(): Int {
        return R.layout.activity_photobrowse
    }

    override fun init() {
        pictureList = intent.getStringArrayListExtra("urls")
        firstDisplayImageIndex = min(intent.getIntExtra("index", firstDisplayImageIndex), pictureList!!.size)

        imageViewPager = findViewById<View>(R.id.viewpager) as BaseAnimCloseViewPager
        setViewPagerAdapter()

        setEnterSharedElementCallback(object : SharedElementCallback() {

            override fun onMapSharedElements(names: List<String>, sharedElements: MutableMap<String, View>) {
                val layout = imageViewPager!!.findViewWithTag<View>(imageViewPager!!.currentItem) as ViewGroup
                val sharedView = layout.findViewById<View>(R.id.image_view)
                sharedElements.clear()
                sharedElements["tansition_view"] = sharedView
            }
        })
    }

    fun startWithElement(context: Activity, urls: ArrayList<String>,
                         firstIndex: Int, view: View?) {
        val intent = Intent(context, PhotoBrowseActivity::class.java)
        intent.putStringArrayListExtra("urls", urls)
        intent.putExtra("index", firstIndex)
        var compat: ActivityOptionsCompat?
        compat = if (view == null) {
            ActivityOptionsCompat.makeSceneTransitionAnimation(context)
        } else {
            ActivityOptionsCompat.makeSceneTransitionAnimation(context, view,
                    "tansition_view")
        }
        ActivityCompat.startActivity(context, intent, compat.toBundle())
    }

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN)
    }

    private fun setViewPagerAdapter() {
        adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return if (pictureList == null) 0 else pictureList!!.size
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                val layout = `object` as View
                container.removeView(layout)
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                val layout: View = LayoutInflater.from(this@PhotoBrowseActivity).inflate(R.layout.layout_browse, null)
                container.addView(layout)
                layout.tag = position

                if (position == firstDisplayImageIndex) {
                    onViewPagerSelected(position)
                }

                return layout

            }

            override fun getItemPosition(`object`: Any): Int {
                return POSITION_NONE
            }
        }

        imageViewPager!!.adapter = adapter
        imageViewPager!!.offscreenPageLimit = 1
        imageViewPager!!.currentItem = firstDisplayImageIndex
        imageViewPager!!.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                if (positionOffset == 0f && newPageSelected) {
                    newPageSelected = false
                    onViewPagerSelected(position)
                }
            }

            override fun onPageSelected(position: Int) {
                newPageSelected = true
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        imageViewPager!!.setiAnimClose(object : BaseAnimCloseViewPager.IAnimClose {
            override fun canDrag(): Boolean {
                return canDrag
            }

            override fun onPictureClick() {
                finishAfterTransition()
            }

            override fun onPictureRelease(view: View) {
                finishAfterTransition()
            }
        })
    }

    var onClickListener: View.OnClickListener = View.OnClickListener { finishAfterTransition() }

    private fun onViewPagerSelected(position: Int) {
        updateCurrentImageView(position)
        setImageView(pictureList!![position])
    }

    /**
     * 设置图片
     *
     * @param path
     */
    private fun setImageView(path: String) {
        if (mCurImage!!.drawable != null)
        //判断是否已经加载了图片，避免闪动
            return
        if (TextUtils.isEmpty(path)) {
            mCurImage!!.setBackgroundColor(Color.GRAY)
            return
        }
        canDrag = false
        Glide.with(this).load(path).into(mCurImage!!)
    }

    // 初始化每个view的image
    protected fun updateCurrentImageView(position: Int) {
        val currentLayout = imageViewPager!!.findViewWithTag<View>(position)
        if (currentLayout == null) {
            ViewCompat.postOnAnimation(imageViewPager!!) { updateCurrentImageView(position) }
            return
        }
        mCurImage = currentLayout.findViewById(R.id.image_view) as ImageView
        imageViewPager!!.setCurrentShowView(mCurImage)
    }

    override fun finishAfterTransition() {
        val intent = Intent()
        intent.putExtra("index", imageViewPager!!.currentItem)
        setResult(Activity.RESULT_OK, intent)
        super.finishAfterTransition()
    }

    override fun initListener() {
    }

    override fun loadData() {
    }

    override fun isFullScreen(): Boolean {
        return true
    }

    override fun initCustomerStatusManager() {
    }

    override fun createPresenter() {
    }

    override fun retry() {
    }

    override fun showLoading() {
    }

    override fun hideLoading() {
    }

}
